<template>
  <div class="dashboard-page">
    <!-- 关键指标卡片 -->
    <div class="metrics-grid">
      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon orders">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ dashboardData.totalOrders }}</div>
            <div class="metric-label">总订单数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon gmv">
            <el-icon><Money /></el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-value">¥{{ formatNumber(dashboardData.totalGmv) }}</div>
            <div class="metric-label">总GMV</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon users">
            <el-icon><User /></el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ dashboardData.totalUsers }}</div>
            <div class="metric-label">总用户数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="metric-card">
        <div class="metric-content">
          <div class="metric-icon products">
            <el-icon><Goods /></el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-value">{{ dashboardData.totalProducts }}</div>
            <div class="metric-label">总商品数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 今日数据 -->
    <el-card class="today-card">
      <template #header>
        <span>今日数据</span>
      </template>
      <div class="today-metrics">
        <div class="today-item">
          <span class="today-label">今日订单：</span>
          <span class="today-value">{{ dashboardData.todayOrders }} 单</span>
        </div>
        <div class="today-item">
          <span class="today-label">今日GMV：</span>
          <span class="today-value">¥{{ formatNumber(dashboardData.todayGmv) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <el-card class="chart-card">
        <template #header>销售趋势（最近7天）</template>
        <div ref="salesChartRef" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>用户增长趋势</template>
        <div ref="userChartRef" class="chart"></div>
      </el-card>
    </div>

    <div class="charts-grid">
      <el-card class="chart-card">
        <template #header>品牌表现</template>
        <div ref="brandChartRef" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>订单状态分布</template>
        <div ref="orderStatusChartRef" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, ref, reactive } from 'vue'
import { ShoppingCart, Money, User, Goods } from '@element-plus/icons-vue'
import { reportService, type DashboardData, type SalesTrendData, type UserStatisticsData, type BrandPerformanceData, type OrderStatusData } from '@/api/reportService'

echarts.use([
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
])

const salesChartRef = ref<HTMLDivElement | null>(null)
const userChartRef = ref<HTMLDivElement | null>(null)
const brandChartRef = ref<HTMLDivElement | null>(null)
const orderStatusChartRef = ref<HTMLDivElement | null>(null)

const dashboardData = reactive<DashboardData>({
  totalOrders: 0,
  totalGmv: 0,
  totalUsers: 0,
  totalProducts: 0,
  todayOrders: 0,
  todayGmv: 0,
  yesterdayOrders: 0,
  yesterdayGmv: 0,
  yesterdayNewUsers: 0,
  yesterdayNewProducts: 0,
  orderChange: 0,
  revenueChange: 0,
  userChange: 0,
  productChange: 0
})

const salesData = reactive<SalesTrendData>({
  dates: [],
  orderCounts: [],
  dailyGmv: []
})

const userData = reactive<UserStatisticsData>({
  totalUsers: 0,
  newUsers: 0,
  newUsers30: 0,
  dates: [],
  dailyNewUsers: []
})

const brandData = reactive<BrandPerformanceData>({
  brandNames: [],
  productCounts: [],
  totalSales: [],
  totalRevenue: []
})

const orderStatusData = reactive<OrderStatusData>({
  statusNames: [],
  counts: []
})

const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const loadDashboardData = async () => {
  try {
    const data = await reportService.getDashboardData()
    Object.assign(dashboardData, data)
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
  }
}

const loadSalesTrend = async () => {
  try {
    const data = await reportService.getSalesTrend()
    Object.assign(salesData, data)
    initSalesChart()
  } catch (error) {
    console.error('加载销售趋势数据失败:', error)
  }
}

const loadUserStatistics = async () => {
  try {
    const data = await reportService.getUserStatistics()
    Object.assign(userData, data)
    initUserChart()
  } catch (error) {
    console.error('加载用户统计数据失败:', error)
  }
}

const loadBrandPerformance = async () => {
  try {
    const data = await reportService.getBrandPerformance()
    Object.assign(brandData, data)
    initBrandChart()
  } catch (error) {
    console.error('加载品牌表现数据失败:', error)
  }
}

const loadOrderStatusDistribution = async () => {
  try {
    const data = await reportService.getOrderStatusDistribution()
    Object.assign(orderStatusData, data)
    initOrderStatusChart()
  } catch (error) {
    console.error('加载订单状态数据失败:', error)
  }
}

const initSalesChart = () => {
  if (!salesChartRef.value) return
  
  const chart = echarts.init(salesChartRef.value)
  chart.setOption({
    tooltip: { 
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: { 
      data: ['订单数', 'GMV(¥)'],
      bottom: 0
    },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 50 
    },
    xAxis: { 
      type: 'category', 
      data: salesData.dates,
      axisLabel: { rotate: 45 }
    },
    yAxis: [
      { 
        type: 'value', 
        name: '订单数',
        position: 'left'
      },
      { 
        type: 'value', 
        name: 'GMV(¥)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        data: salesData.orderCounts,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: 'GMV(¥)',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        data: salesData.dailyGmv,
        itemStyle: { color: '#67C23A' }
      }
    ]
  })
}

const initUserChart = () => {
  if (!userChartRef.value) return
  
  const chart = echarts.init(userChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 30 
    },
    xAxis: { 
      type: 'category', 
      data: userData.dates,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [
      {
        type: 'bar',
        data: userData.dailyNewUsers,
        itemStyle: { color: '#E6A23C' }
      }
    ]
  })
}

const initBrandChart = () => {
  if (!brandChartRef.value) return
  
  const chart = echarts.init(brandChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { bottom: 0 },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 50 
    },
    xAxis: { 
      type: 'category', 
      data: brandData.brandNames,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: brandData.totalSales,
        itemStyle: { color: '#F56C6C' }
      }
    ]
  })
}

const initOrderStatusChart = () => {
  if (!orderStatusChartRef.value) return
  
  const chart = echarts.init(orderStatusChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: '60%',
        data: orderStatusData.statusNames.map((name, index) => ({
          name,
          value: orderStatusData.counts[index]
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

onMounted(async () => {
  await Promise.all([
    loadDashboardData(),
    loadSalesTrend(),
    loadUserStatistics(),
    loadBrandPerformance(),
    loadOrderStatusDistribution()
  ])
})
</script>

<style scoped>
.dashboard-page {
  padding: 20px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.metric-card {
  border-radius: 8px;
}

.metric-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.metric-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.metric-icon.orders {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.metric-icon.gmv {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.metric-icon.users {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.metric-icon.products {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
}

.today-card {
  margin-bottom: 20px;
}

.today-metrics {
  display: flex;
  gap: 40px;
}

.today-item {
  display: flex;
  align-items: center;
}

.today-label {
  font-size: 16px;
  color: #606266;
  margin-right: 10px;
}

.today-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart {
  width: 100%;
  height: 350px;
}

@media (max-width: 768px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
  
  .metrics-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .today-metrics {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
